package com.wxtwxt.ruralmall.product.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

import com.wxtwxt.ruralmall.common.utils.R;
import com.wxtwxt.ruralmall.common.valid.AddGroup;
import com.wxtwxt.ruralmall.common.valid.UpdateGroup;
import com.wxtwxt.ruralmall.product.service.CategoryBrandRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.wxtwxt.ruralmall.product.entity.BrandEntity;
import com.wxtwxt.ruralmall.product.service.BrandService;
import com.wxtwxt.ruralmall.common.utils.PageUtils;

import javax.annotation.Resource;


/**
 * 品牌
 *
 * @author Wxt
 * @email wxt23787@126.com
 * @date 2023-01-30 19:53:31
 */
@EnableTransactionManagement
@RestController
@RequestMapping("product/brand")
public class BrandController {
    @Resource
    private BrandService brandService;
    @Resource
    private CategoryBrandRelationService categoryBrandRelationService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = brandService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{brandId}")
    public R info(@PathVariable("brandId") Long brandId){
		BrandEntity brand = brandService.getById(brandId);

        return R.ok().put("brand", brand);
    }

    /**
     * 保存
     * @param brand 品牌信息实体类
     * @return R
     */
    @Transactional
    @RequestMapping("/save")
    public R save(@Validated({AddGroup.class}) @RequestBody BrandEntity brand) {
		brandService.save(brand);
        return R.ok();
    }

    /**
     * 修改
     */
    @Transactional
    @RequestMapping("/update")
    public R update(@Validated({UpdateGroup.class}) @RequestBody BrandEntity brand){
        if(StringUtils.isNotEmpty(brand.getName())) {
            categoryBrandRelationService.updateBrandName(brand.getBrandId(), brand.getName());
        }
		brandService.updateById(brand);
        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] brandIds){
		brandService.removeByIds(Arrays.asList(brandIds));

        return R.ok();
    }

}
